﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.ComponentModel;
using System.Xml;
using System.Globalization;

namespace Sobiens.Web.Controls.SDXDataGrid
{
    public delegate void EH_OnUpdate(object sender, OnUpdateEventArgs e);

    /// <summary>
    /// Summary description for ServerControl1
    /// </summary>
    public class ServerControl1 : System.Web.UI.WebControls.GridView, IScriptControl
    {
        // Fields
        private ScriptManager _scriptManager;

        private ScriptManager ScriptManager
        {
            get
            {
                if (this._scriptManager == null)
                {
                    Page page = this.Page;
                    this._scriptManager = System.Web.UI.ScriptManager.GetCurrent(page);
                    if (this._scriptManager == null)
                    {
                        throw new InvalidOperationException("Script manager is required!");
                    }
                }
                return this._scriptManager;
            }
        }

        public ServerControl1()
        {
            this.LoadDefaultStyles();
        }

        public IEnumerable<ScriptDescriptor>
                GetScriptDescriptors()
        {
            ScriptControlDescriptor descriptor = new ScriptControlDescriptor("Sobiens.Web.Controls.SDXDataGrid.ClientControl1", this.ClientID);
            yield return descriptor;
        }

        // Generate the script reference
        public IEnumerable<ScriptReference>
                GetScriptReferences()
        {
            List<ScriptReference> references = new List<ScriptReference>();
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Styles.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Datas.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Fields.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Columns.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Cells.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.RowView.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Row.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Rows.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Cells.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Events.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Languages.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.GroupBy.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.GroupByDrager.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.GeneralFunctions.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Navigator.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.Tables.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.CustomColumns.js", this.GetType().Assembly.FullName));
            references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.js.SDXGrid.js", this.GetType().Assembly.FullName));

            //references.Add(new ScriptReference("Sobiens.Web.Controls.SDXDataGrid.ClientControl1.js", this.GetType().Assembly.FullName));
            return references;
        }

                private bool debugMode = false;
        public bool DebugMode
        {
            get
            {
                return debugMode;
            }
            set
            {
                debugMode = value;
            }
        }

        private bool allowEditTemplate = false;
        public bool AllowEditTemplate
        {
            get
            {
                return allowEditTemplate;
            }
            set
            {
                allowEditTemplate = value;
            }
        }
        private bool allowEdit = true;
        public bool AllowEdit
        {
            get
            {
                return allowEdit;
            }
            set
            {
                allowEdit = value;
            }
        }
        private bool allowDelete = true;
        public bool AllowDelete
        {
            get
            {
                return allowDelete;
            }
            set
            {
                allowDelete = value;
            }
        }
        private bool allowAdd = true;
        public bool AllowAdd
        {
            get
            {
                return allowAdd;
            }
            set
            {
                allowAdd = value;
            }
        }
        private bool allowSearch = true;
        public bool AllowSearch
        {
            get
            {
                return allowSearch;
            }
            set
            {
                allowSearch = value;
            }
        }
        private bool allowGroupBy = true;
        public bool AllowGroupBy
        {
            get
            {
                return allowGroupBy;
            }
            set
            {
                allowGroupBy = value;
            }
        }
        private bool allowResize = true;
        public bool AllowResize
        {
            get
            {
                return allowResize;
            }
            set
            {
                allowResize = value;
            }
        }


        private string resourcePath = String.Empty ;
        public string ResourcePath
        {
            get
            {
                if (resourcePath == String.Empty)
                {
                    return "sdxgrid";
                }
                else
                {
                    if (resourcePath.ToString().EndsWith("/") == true || resourcePath.ToString().EndsWith("\\") == true)
                    {
                        return resourcePath;
                    }
                    else
                    {
                        return resourcePath + "/";
                    }
                }
            }
            set
            {
                resourcePath = value;
            }
        }
        private string JSPath
        {
            get
            {
                return this.resourcePath + "/js/";
            }
        }
        private string CSSPath
        {
            get
            {
                return this.resourcePath + "/css/";
            }
        }
        private string IMGPath
        {
            get
            {
                return this.resourcePath + "/images/";
            }
        }
        

        #region STYLES
		private TableItemStyle searchStyle;
		[
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		NotifyParentProperty(true),
		PersistenceMode(PersistenceMode.InnerProperty),
		Category("Style")
		]
		public TableItemStyle SearchStyle
		{
			get
			{
				if(searchStyle == null)
				{
					searchStyle = new TableItemStyle();
					if(IsTrackingViewState)
					{
						((IStateManager)searchStyle).TrackViewState();
					}
				}
				return searchStyle ;
			}
			set
			{
				searchStyle = value;
			}
		}

		private TableStyle groupByTableStyle;
		[
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		NotifyParentProperty(true),
		PersistenceMode(PersistenceMode.InnerProperty),
		Category("Style")
		]
		public TableStyle GroupByTableStyle
		{
			get
			{
				if(groupByTableStyle == null)
				{
					groupByTableStyle = new TableStyle();
					if(IsTrackingViewState)
					{
						((IStateManager)groupByTableStyle).TrackViewState();
					}
				}
				return groupByTableStyle;
			}
			set
			{
				groupByTableStyle = value;
			}
		}
		private TableItemStyle groupByTableItemStyle;
		[
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		NotifyParentProperty(true),
		PersistenceMode(PersistenceMode.InnerProperty),
		Category("Style")
		]
		public TableItemStyle GroupByTableItemStyle
		{
			get
			{
				if(groupByTableItemStyle == null)
				{
					groupByTableItemStyle = new TableItemStyle();
					if(IsTrackingViewState)
					{
						((IStateManager)groupByTableItemStyle).TrackViewState();
					}
				}
				return groupByTableItemStyle;
			}
			set
			{
				groupByTableItemStyle = value;
			}
		}
		private TableItemStyle groupByItemStyle;
		[
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		NotifyParentProperty(true),
		PersistenceMode(PersistenceMode.InnerProperty),
		Category("Style")
		]
		public TableItemStyle GroupByItemStyle
		{
			get
			{
				if(groupByItemStyle == null)
				{
					groupByItemStyle = new TableItemStyle();
					if(IsTrackingViewState)
					{
						((IStateManager)groupByItemStyle).TrackViewState();
					}
				}
				return groupByItemStyle;
			}
			set
			{
				groupByItemStyle = value;
			}
		}

		private TableItemStyle selectorItemStyle;
		[
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		NotifyParentProperty(true),
		PersistenceMode(PersistenceMode.InnerProperty),
		Category("Style")
		]
		public TableItemStyle SelectorItemStyle
		{
			get
			{
				if(selectorItemStyle == null)
				{
					selectorItemStyle = new TableItemStyle();
					if(IsTrackingViewState)
					{
						((IStateManager)selectorItemStyle).TrackViewState();
					}
				}
				return selectorItemStyle;
			}
			set
			{
				selectorItemStyle = value;
			}
		}
		private TableStyle navigatorStyle;
		[
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		NotifyParentProperty(true),
		PersistenceMode(PersistenceMode.InnerProperty),
		Category("Style")
		]
		public TableStyle NavigatorStyle
		{
			get
			{
				if(navigatorStyle == null)
				{
					navigatorStyle = new TableStyle();
					if(IsTrackingViewState)
					{
						((IStateManager)navigatorStyle).TrackViewState();
					}
				}
				return navigatorStyle;
			}
			set
			{
				navigatorStyle = value;
			}
		}
		#endregion
		public event EH_OnUpdate OnUpdate;
		protected virtual void E_OnUpdate(OnUpdateEventArgs e)
		{
			if (OnUpdate != null)
			{
				OnUpdate(this, e);
			}
		}

		private void LoadDefaultStyles()
		{
			this.HeaderStyle.BackColor = System.Drawing.Color.Gray ; //System.Drawing.Color.FromArgb(239,235,222) ;
			this.HeaderStyle.BorderColor = System.Drawing.Color.FromArgb(247,239,231) ;
			this.HeaderStyle.Font.Name = "Microsoft Sans Serif";
			this.HeaderStyle.Font.Size = new FontUnit(10) ;

			this.SelectorItemStyle.BackColor = System.Drawing.Color.Gray ; //System.Drawing.Color.FromArgb(239,235,222) ;
			this.SelectorItemStyle.BorderColor = System.Drawing.Color.FromArgb(247,239,231) ;

			this.RowStyle.BorderColor = System.Drawing.Color.FromArgb(173,170,156) ;
            this.RowStyle.Font.Name = "Microsoft Sans Serif";
            this.RowStyle.Font.Size = new FontUnit(10);
            this.RowStyle.BorderColor = System.Drawing.Color.FromArgb(173, 170, 156);
			this.AlternatingRowStyle.BorderColor = System.Drawing.Color.FromArgb(173,170,156) ;
            this.AlternatingRowStyle.Font.Name = "Microsoft Sans Serif";
            this.AlternatingRowStyle.Font.Size = new FontUnit(10);
            this.AlternatingRowStyle.BorderColor = System.Drawing.Color.FromArgb(173, 170, 156);

			this.SelectedRowStyle.BackColor = System.Drawing.Color.FromArgb(49,105,198) ;

//			this.NavigatorStyle.BorderWidth = new Unit(1) ;
			this.NavigatorStyle.BorderColor = System.Drawing.Color.FromArgb(156,154,206) ;
			this.NavigatorStyle.BackColor = System.Drawing.Color.Gray ;

			this.PagerStyle.BackColor = System.Drawing.Color.White ;
			this.PagerStyle.Font.Name = "Microsoft Sans Serif";
			this.PagerStyle.Font.Size = new FontUnit(10) ;

			this.SearchStyle.BackColor = System.Drawing.Color.FromArgb(206,243,206) ; //System.Drawing.Color.Blue  ;
			this.SearchStyle.Font.Name = "Microsoft Sans Serif";
			this.SearchStyle.Font.Size = new FontUnit(10) ;

			this.GroupByTableStyle.CellSpacing = 1;
			this.GroupByTableStyle.CellPadding = 1;
			this.GroupByTableStyle.Font.Name = "Microsoft Sans Serif";
			this.GroupByTableStyle.Font.Size = new FontUnit(10) ;
			this.GroupByTableStyle.BackColor = System.Drawing.Color.Gray ; //System.Drawing.Color.FromArgb(173,170,156) ;

			this.GroupByTableItemStyle.BackColor = System.Drawing.Color.Silver ;  //System.Drawing.Color.FromArgb(239,235,222) ;
			this.GroupByTableItemStyle.ForeColor = System.Drawing.Color.White ;  //System.Drawing.Color.FromArgb(173,170,156) ;

			this.BorderWidth = new Unit(1) ;
			this.BorderColor = System.Drawing.Color.FromArgb(173,170,156) ;
		}

		public void AcceptChanges()
		{
			System.Web.HttpContext.Current.Response.Clear() ; 
			System.Web.HttpContext.Current.Response.Write("true" + Environment.NewLine ) ; 
		}

        private object GetDataSource()
        {
            object dataSource = null;
            if (this.DataSource != null)
            {
                dataSource = this.DataSource;
            }
            else if (this.DataSourceID != "")
            {
                object datasource = null;
                foreach (Control control in this.Parent.Controls)
                {
                    if (control.ID == this.DataSourceID)
                    {
                        datasource = control;
                    }
                }
                if (datasource != null)
                {
                    if (typeof(AccessDataSource) == datasource.GetType())
                    {
                        AccessDataSource accessDataSource = (AccessDataSource)datasource;
                        dataSource = accessDataSource.Select(new DataSourceSelectArguments());
                    }
                    else if (typeof(SqlDataSource) == datasource.GetType())
                    {
                        SqlDataSource sqlDataSource = (SqlDataSource)datasource;
                        dataSource = sqlDataSource.Select(new DataSourceSelectArguments());
                    }

                }
            }
            return dataSource;
        }
        protected override void OnLoad(EventArgs e)
        {
            if (System.Web.HttpContext.Current.Request.Form.ToString().IndexOf("JLXGridResponse") > 0)
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                string xml1 = System.Web.HttpContext.Current.Server.UrlDecode(System.Web.HttpContext.Current.Request.Form.ToString());
                doc.LoadXml(xml1);
                string xml = doc.ChildNodes[1].ChildNodes[0].ChildNodes[0].ChildNodes[0].InnerText;
                xml = xml.Replace("<![CDATA_BEGIN[", "<![CDATA[").Replace("]]END>", "]]>");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);

                System.Data.DataSet ds = new System.Data.DataSet();
                System.Data.DataTable table = ds.Tables.Add(xmlDoc.ChildNodes[1].Attributes["TableName"].InnerText);

                XmlNodeList columnsNodes = xmlDoc.SelectNodes("DataSet/Columns");
                foreach (XmlNode node in columnsNodes[0].ChildNodes)
                {
                    table.Columns.Add(node["Name"].InnerText, Type.GetType(node["DataType"].InnerText));
                }
                table.Columns.Add("SDXGridRowIndex");

                XmlNodeList modifiedOriginalDataNodes = xmlDoc.SelectNodes("DataSet/ModifiedOriginalData");
                if (modifiedOriginalDataNodes.Count > 0)
                {
                    for (int i = 0; i < modifiedOriginalDataNodes.Count; i++)
                    {
                        XmlNode node = modifiedOriginalDataNodes[i];
                        System.Data.DataRow row = table.NewRow();
                        foreach (System.Data.DataColumn column in table.Columns)
                        {
                            if (node[column.ColumnName] != null)
                                row[column.ColumnName] = node[column.ColumnName].InnerText;
                            else
                                row[column.ColumnName] = DBNull.Value;
                        }
                        row["SDXGridRowIndex"] = node["SDXGridRowIndex"].InnerText;
                        table.Rows.Add(row);
                    }
                }
                table.AcceptChanges();

                XmlNodeList modifiedNodes = xmlDoc.SelectNodes("DataSet/Modified");
                if (modifiedNodes.Count > 0)
                {
                    for (int i = 0; i < modifiedNodes.Count; i++)
                    {
                        XmlNode node = modifiedNodes[i];
                        System.Data.DataRow row = table.Select("SDXGridRowIndex='" + node["SDXGridRowIndex"].InnerText + "'")[0];
                        foreach (System.Data.DataColumn column in table.Columns)
                        {
                            if (node[column.ColumnName] != null)
                                row[column.ColumnName] = node[column.ColumnName].InnerText;
                            else
                                row[column.ColumnName] = DBNull.Value;
                        }
                    }
                }

                XmlNodeList deletedNodes = xmlDoc.SelectNodes("DataSet/Deleted");
                if (deletedNodes.Count > 0)
                {
                    for (int i = 0; i < deletedNodes.Count; i++)
                    {
                        XmlNode node = deletedNodes[i];
                        System.Data.DataRow row = table.Select("SDXGridRowIndex='" + node["SDXGridRowIndex"].InnerText + "'")[0];
                        row.Delete();
                    }
                }

                XmlNodeList addedNodes = xmlDoc.SelectNodes("DataSet/Added");
                if (addedNodes.Count > 0)
                {
                    for (int i = 0; i < addedNodes.Count; i++)
                    {
                        XmlNode node = addedNodes[i];
                        System.Data.DataRow row = table.Select("SDXGridRowIndex='" + node["SDXGridRowIndex"].InnerText + "'")[0];
                        foreach (System.Data.DataColumn column in table.Columns)
                        {
                            if (node[column.ColumnName] != null)
                                row[column.ColumnName] = node[column.ColumnName].InnerText;
                            else
                                row[column.ColumnName] = DBNull.Value;
                        }
                        row["SDXGridRowIndex"] = node["SDXGridRowIndex"].InnerText;
                        table.Rows.Add(row);
                    }
                }
                OnUpdateEventArgs eventArgs = new OnUpdateEventArgs(table.DataSet);
                //this.EmptyDataTemplate
                E_OnUpdate(eventArgs);
                System.Web.HttpContext.Current.Response.End();
            }
            base.OnLoad(e);
        }

		private string ConvertToHtmlData(string data)
		{
			return System.Web.HttpUtility.HtmlEncode( data.Replace(Environment.NewLine,"\\n").Replace("\"","\\\"") ) ;
		}
		private string ConvertToHtmlData(System.Data.DataRow row, System.Data.DataColumn column)
		{
			if(column.DataType == typeof(string))
			{
				return this.ConvertToHtmlData(row[column].ToString()) ;
			}
			else if(column.DataType == typeof(DateTime))
			{
				if(row[column] != DBNull.Value)
				{
					DateTime date =  (DateTime)row[column] ;
					return "new Date(" + date.Year.ToString() + "," + date.Month.ToString() + "," + date.Day.ToString() + ")" ;
				}
				else
				{
					return "null" ;
				}
			}
			else if( (column.DataType == typeof(int)) || (column.DataType == typeof(short)) || (column.DataType == typeof(long)) )
			{
				if(row[column] != DBNull.Value)
				{
					return row[column].ToString() ;
				}
				else
				{
					return "0" ;
				}
			}
			else if(column.DataType == typeof(bool))
			{
				if(row[column] != DBNull.Value)
				{
					return ((bool)row[column]?"1":"0") ;
				}
				else
				{
					return "0" ;
				}
			}
			return "";
		}
		private string GetRowHTML(System.Data.DataTable table, System.Data.DataRow row)
		{
			string html = this.ClientID + ".Datas.InsertData(new Array(";
			for(int nX=0;nX<this.Columns.Count;nX++)
			{
				DataControlField dataGridField = this.Columns[nX] ;

                if (dataGridField is BoundField)
				{
                    BoundField boundField = (BoundField)dataGridField;
                    System.Data.DataColumn column = table.Columns[boundField.DataField];
					if(column.DataType == typeof(string))
					{
						html += "\"" + this.ConvertToHtmlData(row,column) + "\"," ;
					}
					else
					{
						html += this.ConvertToHtmlData(row,column) + "," ;
					}
				}
			}
			html = html.TrimEnd(',') ;
			html += "))" ;
			return html ;
		}
		private string GetColumnHTML(System.Data.DataTable table, DataControlField dataGridField, string className, int index)
		{
			string html = "" ;
            if (dataGridField is BoundField)
			{
                bool isRelationColumn = false;
                BoundField boundField = (BoundField)dataGridField ;
				System.Data.DataColumn column = table.Columns[boundField.DataField] ;
				foreach( System.Data.DataRelation relation in table.ParentRelations )
				{
					if(relation.ChildColumns[0].ColumnName == column.ColumnName)
					{
						
						html +="var optionsx = new Array();" + Environment.NewLine ;
						for(int nX=0;nX<relation.ParentTable.Rows.Count;nX++)
						{
							System.Data.DataRow row = relation.ParentTable.Rows[nX] ;
							html += "optionsx[" + nX.ToString() + "] = new Array();" + Environment.NewLine +
								    "optionsx[" + nX.ToString() + "][0] = \"" + this.ConvertToHtmlData(row[0].ToString()) + "\"" + Environment.NewLine +
									"optionsx[" + nX.ToString() + "][1] = \"" + this.ConvertToHtmlData(row[1].ToString())  + "\"" + Environment.NewLine ;
						}
						html += "sdxSelectboxField.DataSource = optionsx" + Environment.NewLine +
                                "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxSelectboxField,\"" + column.ColumnName + "\", \"" + boundField.HeaderText + "\", true,\"SmlTblTitle3\")" + Environment.NewLine;
                        isRelationColumn = true;
						break ;
					}
				}
                if (isRelationColumn == true) { }
				else if(column.DataType == typeof(string))
				{
                    html += "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxStringField,\"" + column.ColumnName + "\",\"" + boundField.HeaderText + "\", true,\"" + className + "\")" + Environment.NewLine;
				}
				else if(column.DataType == typeof(DateTime))
				{
                    html += "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxDateField,\"" + column.ColumnName + "\",\"" + boundField.HeaderText + "\", true,\"" + className + "\")" + Environment.NewLine;
				}
				else if(column.DataType == typeof(int))
				{
                    html += "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxNumberField,\"" + column.ColumnName + "\",\"" + boundField.HeaderText + "\", true,\"" + className + "\")" + Environment.NewLine;
				}
				else if(column.DataType == typeof(short))
				{
                    html += "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxNumberField,\"" + column.ColumnName + "\",\"" + boundField.HeaderText + "\", true,\"" + className + "\")" + Environment.NewLine;
				}
				else if(column.DataType == typeof(long))
				{
                    html += "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxNumberField,\"" + column.ColumnName + "\",\"" + boundField.HeaderText + "\", true,\"" + className + "\")" + Environment.NewLine;
				}
				else if(column.DataType == typeof(bool))
				{
                    html += "var gridColumn = " + this.ClientID + ".Columns.InsertColumn( sdxBooleanField,\"" + column.ColumnName + "\",\"" + boundField.HeaderText + "\", true,\"" + className + "\")" + Environment.NewLine;
				}
				html += "gridColumn.AllowDBNull = " + column.AllowDBNull.ToString().ToLower() + Environment.NewLine +
					"gridColumn.AutoIncrement = " + column.AutoIncrement.ToString().ToLower() + Environment.NewLine +
					"gridColumn.AutoIncrementStep = " + column.AutoIncrementStep.ToString() + Environment.NewLine +
					"gridColumn.DefaultValue = '" + column.DefaultValue.ToString() + "'" + Environment.NewLine +
                    "gridColumn.DataType = '" + column.DataType.ToString() + "'" + Environment.NewLine +
                    "gridColumn.ColumnName = '" + column.ColumnName.ToString() + "'" + Environment.NewLine +
                    "gridColumn.ReadOnly = " + boundField.ReadOnly.ToString().ToLower() + Environment.NewLine +
                    "gridColumn.Visible = " + boundField.Visible.ToString().ToLower() + Environment.NewLine +
					"gridColumn.Unique = " + column.Unique.ToString().ToLower() + Environment.NewLine ;
			}
			return html ;
		}

		private string GetFontNames(string[] _names)
		{
			string names = "" ;
			for(int nX=0;nX<_names.Length;nX++)
			{
				names += _names[0] + "," ;
			}
			if(names != "")
				names = names.Substring(0,names.Length -1) ;
			return names ;
		}
		private string GetFontHTML(FontInfo font, string objectString)
		{
			return  objectString + ".Bold = " + font.Bold.ToString().ToLower() + Environment.NewLine +
				objectString + ".Italic = " + font.Italic.ToString().ToLower() + Environment.NewLine +
				(font.Names.Length>0?objectString + ".Names = '" + this.GetFontNames(font.Names) + "'" + Environment.NewLine:"") +
				objectString + ".Overline = " + font.Overline.ToString().ToLower() + Environment.NewLine +
				(font.Size!= FontUnit.Empty?objectString + ".Size = '" + font.Size.Unit.Value.ToString().ToLower() + "'" + Environment.NewLine:"") +
				objectString + ".Strikeout = " + font.Strikeout.ToString().ToLower() + Environment.NewLine +
				objectString + ".Underline = " + font.Underline.ToString().ToLower() + Environment.NewLine ;
		}

		private string GetStyleHTML(TableStyle style, string objectString)
		{
			return  (style.BackColor!= System.Drawing.Color.Empty?objectString + ".BackColor = '" + GetColorString(style.BackColor) + "'" + Environment.NewLine:"") +
				(style.BorderColor!= System.Drawing.Color.Empty?objectString + ".BorderColor = '" + GetColorString(style.BorderColor) + "'" + Environment.NewLine:"") +
				(style.BorderStyle!= BorderStyle.NotSet?objectString + ".BorderStyle = '" + style.BorderStyle.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.BorderWidth!= Unit.Empty?objectString + ".BorderWidth = '" + style.BorderWidth.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.CssClass!= ""?objectString + ".CssClass = '" + style.CssClass.ToString().ToLower() + "'" + Environment.NewLine:"") +
				this.GetFontHTML(style.Font,objectString + ".Font") +
				(style.ForeColor!= System.Drawing.Color.Empty?objectString + ".ForeColor = '" + GetColorString(style.ForeColor) + "'" + Environment.NewLine:"") +
				(style.Height!= Unit.Empty?objectString + ".Height = '" + style.Height.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.HorizontalAlign!= HorizontalAlign.NotSet?objectString + ".HorizontalAlign = '" + style.HorizontalAlign.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.Width!= Unit.Empty?objectString + ".Width = '" + style.Width.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.CellPadding!= Unit.Empty?objectString + ".CellPadding = " + style.CellPadding.ToString().ToLower() + Environment.NewLine:"") +
				(style.CellSpacing!= Unit.Empty?objectString + ".CellSpacing = " + style.CellSpacing.ToString().ToLower() + Environment.NewLine:"") +
				objectString + ".GridLines= '" + GetGridLinesString(style.GridLines) + "'" + Environment.NewLine ;
		}
		private string GetStyleHTML(GridView grid, string objectString)
		{
			return  (grid.BackColor!= System.Drawing.Color.Empty?objectString + ".BackColor = '" + GetColorString(grid.BackColor) + "'" + Environment.NewLine:"") +
				(grid.BorderColor!= System.Drawing.Color.Empty?objectString + ".BorderColor = '" + GetColorString(grid.BorderColor) + "'" + Environment.NewLine:"") +
				(grid.BorderStyle!= BorderStyle.NotSet?objectString + ".BorderStyle = '" + grid.BorderStyle.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(grid.BorderWidth!= Unit.Empty?objectString + ".BorderWidth = '" + grid.BorderWidth.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(grid.CssClass!= ""?objectString + ".CssClass = '" + grid.CssClass.ToString().ToLower() + "'" + Environment.NewLine:"") +
				this.GetFontHTML(grid.Font,objectString + ".Font") +
				(grid.ForeColor!= System.Drawing.Color.Empty?objectString + ".ForeColor = '" + GetColorString(grid.ForeColor) + "'" + Environment.NewLine:"") +
				(grid.Height!= Unit.Empty?objectString + ".Height = '" + grid.Height.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(grid.HorizontalAlign!= HorizontalAlign.NotSet?objectString + ".HorizontalAlign = '" + grid.HorizontalAlign.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(grid.Width!= Unit.Empty?objectString + ".Width = '" + grid.Width.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(grid.CellPadding!= Unit.Empty?objectString + ".CellPadding = " + grid.CellPadding.ToString().ToLower() + Environment.NewLine:"") +
				(grid.CellSpacing!= Unit.Empty?objectString + ".CellSpacing = " + grid.CellSpacing.ToString().ToLower() + Environment.NewLine:"") +
				objectString + ".GridLines= '" + GetGridLinesString(grid.GridLines) + "'" + Environment.NewLine ;
		}
		private string GetStyleHTML(TableItemStyle style, string objectString)
		{
			return  (style.BackColor!= System.Drawing.Color.Empty?objectString + ".BackColor = '" + GetColorString(style.BackColor) + "'" + Environment.NewLine:"") +
				(style.BorderColor!= System.Drawing.Color.Empty?objectString + ".BorderColor = '" + GetColorString(style.BorderColor) + "'" + Environment.NewLine:"") +
				(style.BorderStyle!= BorderStyle.NotSet?objectString + ".BorderStyle = '" + style.BorderStyle.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.BorderWidth!= Unit.Empty?objectString + ".BorderWidth = '" + style.BorderWidth.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.CssClass!= ""?objectString + ".CssClass = '" + style.CssClass.ToString().ToLower() + "'" + Environment.NewLine:"") +
				this.GetFontHTML(style.Font,objectString + ".Font") +
				(style.ForeColor!= System.Drawing.Color.Empty?objectString + ".ForeColor = '" + GetColorString(style.ForeColor) + "'" + Environment.NewLine:"") +
				(style.Height!= Unit.Empty?objectString + ".Height = " + style.Height.ToString().ToLower() + Environment.NewLine:"") +
				(style.HorizontalAlign!= HorizontalAlign.NotSet?objectString + ".HorizontalAlign = '" + style.HorizontalAlign.ToString().ToLower() + "'" + Environment.NewLine:"") +
				(style.VerticalAlign!= VerticalAlign.NotSet?objectString + ".VerticalAlign = " + style.VerticalAlign.ToString().ToLower() + Environment.NewLine:"") +
				(style.Width!= Unit.Empty?objectString + ".Width = " + style.Width.ToString().ToLower() + Environment.NewLine:"") +
				objectString + ".Wrap = " + style.Wrap.ToString().ToLower() + Environment.NewLine ;

		}
		private string GetColorString(System.Drawing.Color color)
		{
			if( color.IsKnownColor == true )
			{
				return color.Name ;
			}
			else if( color.IsNamedColor == true )
			{
				return color.Name ;
			}
			else if( color.IsSystemColor == true )
			{
				return color.Name ;
			}
			else
			{
				return color.Name.Substring(2,6) ;
			}
		}

		private string GetGridLinesString(GridLines gridLines)
		{
			if(gridLines == GridLines.Both)
			{
				return "both";
			}
			else if(gridLines == GridLines.Horizontal)
			{
				return "rows";
			}
			else if(gridLines == GridLines.None)
			{
				return "none";
			}
			else if(gridLines == GridLines.Vertical)
			{
				return "cols";
			}
			return "";
		}
		private Table GetGroupByTable()
		{
			Table groupByTable = new Table() ;
			groupByTable.Width = this.Width ;
			groupByTable.ApplyStyle(this.GroupByTableStyle) ;

			TableRow groupByRow = new TableRow() ;
			TableCell groupByCell = new TableCell() ;
			groupByCell.HorizontalAlign = HorizontalAlign.Left ;
			groupByCell.ColumnSpan = 2 ;
			groupByCell.ApplyStyle(this.GroupByTableStyle) ;
			groupByCell.Text = "Drag Here..." ;

			groupByRow.Cells.Add(groupByCell) ;
			groupByTable.Rows.Add(groupByRow);
			return groupByTable;
		}
		private Table GetNavigatorTable()
		{
			Table navigatorTable = new Table() ;
			navigatorTable.Width = this.Width ;
			navigatorTable.ApplyStyle(this.NavigatorStyle) ;

			TableRow searchRow = new TableRow() ;
			TableCell searchCell = new TableCell() ;
			searchCell.HorizontalAlign = HorizontalAlign.Center ;
			searchCell.ColumnSpan = 2 ;
			searchCell.ApplyStyle(this.SearchStyle) ;
			Image searchImage = new Image();
			searchImage.ImageUrl = this.IMGPath + "images/sp_icoSearch.gif" ;
			searchImage.ImageAlign = ImageAlign.AbsMiddle ;
			searchImage.Style.Add("cursor","pointer") ;
			TextBox searchTextbox = new TextBox();
			searchTextbox.Width = new Unit(100);
			DropDownList searchDropDownList = new DropDownList() ;
			searchDropDownList.Items.Add("All Fields");
			searchCell.Controls.Add(searchImage );
			searchCell.Controls.Add(searchTextbox);
			searchCell.Controls.Add(searchDropDownList );
			searchRow.Cells.Add(searchCell) ;
			navigatorTable.Rows.Add(searchRow);

			TableRow pagerRow = new TableRow() ;
			TableCell pagerCell1 = new TableCell() ;
			pagerCell1.Width = new Unit("50%") ;
			pagerCell1.ApplyStyle(this.PagerStyle) ;
			pagerCell1.HorizontalAlign = HorizontalAlign.Left ;
			Image pagerImage = new Image();
            pagerImage.ImageUrl = this.IMGPath + "images/refresh.gif";
			pagerImage.ImageAlign = ImageAlign.AbsMiddle ;
			pagerImage.Style.Add("cursor","pointer") ;
			DropDownList pagerDropDownList = new DropDownList() ;
			pagerDropDownList.Items.Add(this.PageSize.ToString());
			pagerCell1.Controls.Add(pagerImage );
			pagerCell1.Controls.Add(pagerDropDownList );
			pagerRow.Cells.Add(pagerCell1) ;

			TableCell pagerCell2 = new TableCell() ;
			pagerCell2.ApplyStyle(this.PagerStyle) ;
			pagerCell2.HorizontalAlign = HorizontalAlign.Right ;

			Label pagerLabelLeft = new Label() ;
			pagerLabelLeft.Text = "<< | Previous ";

			TextBox pagerTextbox = new TextBox();
			pagerTextbox.Width = new Unit(20);
			pagerTextbox.Text = "2" ;

			Label pagerLabelRight = new Label() ;
			pagerLabelRight.Text = " / 1 Next | >> ";

			pagerCell2.Controls.Add(pagerLabelLeft);
			pagerCell2.Controls.Add(pagerTextbox);
			pagerCell2.Controls.Add(pagerLabelRight);
			pagerRow.Cells.Add(pagerCell2) ;

			navigatorTable.Rows.Add(pagerRow);
			return navigatorTable ;
		}

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.ScriptManager.RegisterScriptControl(this);
        }

		/// <summary>
		/// Render this control to the output parameter specified.
		/// </summary>
		/// <param name="output"> The HTML writer to write out to </param>
		protected override void Render(HtmlTextWriter output)
		{
			// This try was added. Because you can not Response.Write at the render time
			try
			{
                System.Web.HttpContext.Current.Response.Write("<link href=\"" + this.CSSPath + "spIE.css\" type=\"text/css\" rel=\"stylesheet\" /><link href=\"" + this.CSSPath + "style.css\" type=\"text/css\" rel=\"stylesheet\" />");
			}
			catch
			{
				this.GetGroupByTable().RenderControl(output); 
				this.GetNavigatorTable().RenderControl(output); 
				base.Render(output) ;
				return;
			}
            if (this.EmptyDataTemplate != null)
            {
                TableCell cell = new TableCell();
                this.EmptyDataTemplate.InstantiateIn(cell);
                Table table1 = new Table();
                table1.Attributes.Add("style", "position: absolute;visibility:hidden;z-index:10000");
                table1.ID = this.ClientID + "_SDXGrid_EditTemplate";
                TableRow row1 = new TableRow();
                row1.Cells.Add(cell);
                table1.Rows.Add(row1);
                table1.RenderControl(output);
            }
            else
            {
                this.AllowEditTemplate = false;
            }

			string html = "<div id=\"Div_SDXGrid_" + this.ClientID + "\" style=\"DISPLAY: block; POSITION: relative\"></div>" + Environment.NewLine +
						  "<div style=\"visibility:hidden;position:absolute;left:0px;top:0px;\" id=\"userimg\">SERKANT</div>" + Environment.NewLine +
						  "<script language=\"javascript\">" + Environment.NewLine +
						  this.ClientID + " = new SDXGrid(\"" + this.ClientID + "\",\"Div_SDXGrid_" + this.ClientID + "\",\"Div_SDXGrid_" + this.ClientID + "\")" + Environment.NewLine +
						  this.ClientID + ".RowLimit = 30" + Environment.NewLine +
                          this.ClientID + ".ResourcePath = '" + this.ResourcePath.Replace("\\","\\\\") + "'" + Environment.NewLine +
                          this.ClientID + ".AllowEditTemplate = " + this.AllowEditTemplate.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowEdit = " + this.AllowEdit.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowDelete = " + this.AllowDelete.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowAdd = " + this.AllowAdd.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowSearch = " + this.AllowSearch.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowGroupBy = " + this.AllowGroupBy.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowResize = " + this.AllowResize.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowPaging = " + this.AllowPaging.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".AllowSorting = " + this.AllowSorting.ToString().ToLower() + Environment.NewLine +
                          this.ClientID + ".RowLimit = " + this.PageSize.ToString() + Environment.NewLine +
                          this.GetStyleHTML(this.AlternatingRowStyle, this.ClientID + ".Styles.AlternatingItemStyle") + 
						  this.GetStyleHTML(this.EditRowStyle, this.ClientID + ".Styles.EditItemStyle") + 
						  this.GetStyleHTML(this.FooterStyle, this.ClientID + ".Styles.FooterStyle") + 
						  this.GetStyleHTML(this.HeaderStyle, this.ClientID + ".Styles.HeaderStyle") + 
						  this.GetStyleHTML(this.RowStyle, this.ClientID + ".Styles.ItemStyle") + 
						  this.GetStyleHTML(this.PagerStyle, this.ClientID + ".Styles.PagerStyle") + 
						  this.GetStyleHTML(this.SelectedRowStyle, this.ClientID + ".Styles.SelectedItemStyle") +
						  this.GetStyleHTML(this.GroupByItemStyle, this.ClientID + ".Styles.GroupByItemStyle") +
						  this.GetStyleHTML(this.GroupByTableStyle , this.ClientID + ".Styles.GroupByTableStyle") +
						  this.GetStyleHTML(this.GroupByTableItemStyle , this.ClientID + ".Styles.GroupByTableItemStyle") +
						  this.GetStyleHTML(this.SelectorItemStyle, this.ClientID + ".Styles.SelectorItemStyle") +
						  this.GetStyleHTML(this.NavigatorStyle , this.ClientID + ".Styles.NavigatorStyle") +
						  this.GetStyleHTML(this.SearchStyle , this.ClientID + ".Styles.SearchStyle") +
						  this.GetStyleHTML(this, this.ClientID + ".Styles.Style") ;


			try
			{
                object dataSource = this.GetDataSource();
                if (dataSource != null)
                {
					System.Data.DataTable table ;
                    if (dataSource is System.Data.DataSet)
					{
						if(this.DataMember != null && this.DataMember != "")
						{
                            table = ((System.Data.DataSet)dataSource).Tables[this.DataMember];
						}
						else
						{
                            table = ((System.Data.DataSet)dataSource).Tables[0];
						}
					}
					else
					{
                        table = ((System.Data.DataView)dataSource).Table;
					}

					foreach(System.Data.DataRow row in table.Rows)
					{
						html += this.GetRowHTML(table,row) + Environment.NewLine ;
					}

					for(int nX=0;nX<this.Columns.Count;nX++)
					{
						DataControlField column = this.Columns[nX] ;
						html += this.GetColumnHTML(table,column,"SmlTblTitle3",nX) ;
					}

					html += this.ClientID + ".DataSetName = '" + table.DataSet.DataSetName + "'" + Environment.NewLine +
							this.ClientID + ".DataSetTableName = '" + table.TableName + "'" + Environment.NewLine  +
							this.ClientID + ".DataSetNamespace = '" + table.DataSet.Namespace + "'" + Environment.NewLine +
							this.ClientID + ".Datas.AcceptChanges()" + Environment.NewLine +
							this.ClientID + ".Initialize()" + Environment.NewLine +
							"</script>" ;
					output.Write(html);
				}
				else
				{
					output.Write("null");
				}
                //base.Render(output);
                if (!base.DesignMode)
                {
                    this.ScriptManager.RegisterScriptDescriptors(this);
                }

			}
			catch(Exception ex)
			{
				output.Write("exception:" + ex.Message );
			}
		}

    }
}